package jsp;

import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/13 11:05
 * Version:1.0-SNAPSHOT
 * Description:
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        if("/login.user".equals(path)){
            login(request,response);
        }
        if("/logout.user".equals(path)){
            logout(request,response);
        }
        if("/register.user".equals(path)){
            register(request,response);
        }
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            // 用户名不能重复
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            rs = ps.executeQuery();
            if(rs.next()){
                // 如果在数据库中查询到了数据
                // 说明当前用户名已经被注册
                request.setAttribute("registerMsg","该用户已经被注册");
                request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
                return;
            }
            // 如果没有查询到数据,则表示该用户尚未被注册
            // 开始注册
            sql = new StringBuffer()
                    .append(" insert into")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,phone);
            ps.setString(4,address);
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        }
    }
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
//        request.getSession().removeAttribute("user");
        response.sendRedirect(request.getContextPath()+"/jsp/main.jsp");
    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 获取用户输入的验证码
        String code = request.getParameter("code");
        // 获取验证码图片的内容
        String image = (String) request.getSession().getAttribute("code");
        // 在实际开发中,进行校验的时候要求优先使用验证码进行校验
        // 如果验证码校验失败,则不需要再进行JDBC操作,这些效率较高
        if(!code.equals(image)){
            request.setAttribute("loginMsg","验证码不正确");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }

        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8";
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            while(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                // 当用户名与密码正确
                // 将查询出来的用户信息保存到session中
                request.getSession().setAttribute("user",user);
                // 用户功能完成之后,会进入另一个业务中,此时一般使用重定向
                response.sendRedirect(request.getContextPath()+"/jsp/main.jsp");
                // 此时登录成功的流程结束,需要跳出当前方法,不能继续执行
                return;
            }
            // 如果没有查询到对应信息,说明用户名或者密码出现了问题
            request.setAttribute("loginMsg","用户名或密码错误");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }

    }

}
